import { Router, Request, Response, NextFunction } from 'express';
import { executeCode } from '../services/executionService';
import { validateExecuteRequest } from '../validators/executeValidator';
import { ApiError } from '../middleware/errorHandler';
import { logger } from '../utils/logger';

const router = Router();

/**
 * @route POST /api/execute
 * @desc 执行代码
 * @access Public
 */
router.post('/', async (req: Request, res: Response, next: NextFunction) => {
  try {
    // 验证请求
    const { error, value } = validateExecuteRequest(req.body);
    if (error) {
      throw new ApiError(400, `Invalid request: ${error.message}`);
    }

    const { language, code, input = '', timeout = 10000 } = value;

    logger.info(`Executing ${language} code, length: ${code.length}`);

    // 执行代码
    const result = await executeCode(language, code, input, timeout);

    // 返回结果
    return res.status(200).json({
      status: 'success',
      data: {
        output: result.output,
        executionTime: result.executionTime,
        memoryUsage: result.memoryUsage,
        exitCode: result.exitCode
      }
    });
  } catch (err) {
    if (err instanceof ApiError) {
      return next(err);
    }
    
    logger.error(`Code execution error: ${err instanceof Error ? err.message : 'Unknown error'}`);
    return next(new ApiError(500, 'Code execution failed'));
  }
});

export const executeRoutes = router; 